#include "RingQueue.hpp"
#include "Thread.hpp"
#include <vector>
#include <unistd.h>
#include <string>
#include <ctime>
#include "Task.hpp"

using namespace ThreadModule;
// int number = 15;
int cnt = 66;
using RingQueue_t = RingQueue<Task>;

void Consumer(RingQueue_t &rq, const std::string &name)
{
    while (true)
    {
        //sleep(2);
        Task t;
        rq.Pop(t);
        //std::cout << "consumer name : " << data << ", [" << name << "]" << std::endl;
        t();
    }
}

void Productor(RingQueue_t &rq, const std::string &name)
{

    while (true)
    {
        rq.Enqueue(Download);
        //std::cout << "productor name : " << cnt << ", [" << name << "]" << std::endl;
        // sleep(1);
    }
}

void InitComm(std::vector<Thread<RingQueue_t>> *tds, int num, RingQueue_t &rq, func_t<RingQueue_t> func, const std::string &who)
{
    for (int i = 0; i < num; i++)
    {
        //std::string* name = new std::string( "thread - " + std::to_string(i + 1));
        std::string name = " thread - " + std::to_string(i + 1) + "-" +who;
        //char* name = new char[64]; 
        //snprintf(name,64,"thread - %d", i+1);
        tds->emplace_back(func, rq, name);
        //tds->back().Start();
    }
}

void InitConsumer(std::vector<Thread<RingQueue_t>> *tds, int num, RingQueue_t &rq)
{
    InitComm(tds, num, rq, Consumer,"consymer");
}

void InitProductor(std::vector<Thread<RingQueue_t>> *tds, int num, RingQueue_t &rq)
{
    InitComm(tds, num, rq, Productor,"productor");
}

void WaitAllThread(std::vector<Thread<RingQueue_t>> tds)
{
    for (auto &td : tds)
    {
        td.Join();
    }
}

void StartAll(std::vector<Thread<RingQueue_t>>& threads)
{
    for(auto& thread : threads)
    {
        thread.Start();
    }
}

int main()
{
    RingQueue_t *rq = new RingQueue_t(10);
    std::vector<Thread<RingQueue_t>> threads;
    InitConsumer(&threads, 1, *rq);
    InitProductor(&threads, 1, *rq);
    StartAll(threads);
    WaitAllThread(threads);
    return 0;
}